<script setup>
import { reactive, ref } from "vue";
import uu from "@/util/uu";
import { ElMessage } from "element-plus";

let data = reactive({
  // 所有的表单数据由它装入
  form: {

  },
  // 查勘信息列表
  surveyList: [],
  // 是否添加查勘记录
  isAddBusiness: false,
  dispatchList: [],
  // 调度对象信息
  dispatchForm: {},
  // 是否禁用按钮
  isDisable: true,
  pageNum: 1,
  pageSize: 5,
  total:0,
});
/**
 * 查询所有的查勘信息
 */
const queryAll = () => {
  console.log("开始查询数据");
  console.log("传递的参数为" + JSON.stringify(data.form));
  // http://localhost:8080
  uu.get("/busSurveyInfo/pageList", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      claimReportId: data.form.claimReportId,
    },
  }).then((result) => {
    data.surveyList = result.data.list;
    data.pageNum = result.data.pageNum;
    data.pageSize = result.data.pageSize;
    data.total = result.data.total;
    console.log("接收到的数据为" + JSON.stringify(data.surveyList));
  });
};
queryAll();
/*
  改变页数
 */
const pagesChange = (value) => {
  // alert(value)
  //  console.log(value)
  data.pages = value;
  queryAll();
};
/*
  删除查勘记录
 */
const delBusiness = (id) => {
  // alert(data.form.claimReportId)
  if (id != null) {
    uu.delete("/busSurveyInfo/remove", {
      params: {
        id: id,
      },
    }).then((result) => {
      // alert(result.message)
      if (result.ok) {
        data.success = true; // 显示成功提示
        ElMessage({
          message: result.message,
          type: "success",
        });
        // 关闭对话框
        data.dialogDelVisible = false;
        // 清楚数据
        data.form = {};
        // 刷新页面
        queryAll();
      } else {
        ElMessage.error(result.message); // 显示失败提示
      }
    });
  } else {
    ElMessage.error("删除查勘记录失败，传入方法的id为空"); // 显示失败提示
  }
};
/*
  关闭添加删除对话框
 */
const handleClose = () => {
  data.form = {}; // 清除数据
  data.dialogVisible = false; // 关闭对话框
  // 清除残留验证规则信息，让下次打开不会有上次的残留信息
  ruleFormRef.value.resetFields();
};
/*
  开启添加删除对话框
 */
const dialogBox = (isAdd, id) => {
  // 展开对话框
  data.dialogVisible = true;
  if (isAdd === false) {
    // 此为修改对话框
    if (id != null) {
      console.log("修改查勘信息对话框展开");
      // 根据id获取用户数据
      uu.get("/busSurveyInfo/getById/" + id).then((result) => {
        data.form = result.data;
        console.log("获取到的单个记录信息为" + JSON.stringify(data.form));
        //查询我的调度信息
        queryForDispatchList();
        // 根据查询到的调度信息去查询保单以及报案信息
        queryClaimAndPolicy();
      });
      // 因为请求发送之后会刷新页面，所以这里就把 data.form 的值进行清空，以免带有自己不想要的值去执行queryAll()方法
      data.form = {};
    } else {
      ElMessage.error("获取具体查勘记录时失效，传入方法的id为空"); // 显示失败提示
    }
  } else if (isAdd === true) {
    // 此为添加对话框
    console.log("添加查勘信息对话框展开");
    // 查询我的调度信息
    queryForDispatchList();
    console.log(data.form.province);
  }
  // 将值传递到视图，然后视图判断要显示那些文字， 以及提交时调用那个方法。
  data.isAdd = isAdd;
};
/**
 * 添加查勘记录框可能会导致验证规则残留
 */
const save = (ruleFormRef) => {
  // 重置验证规则，因为子对话框关闭之后再次到达主对话
  // ruleFormRef.resetFields();
  // ruleFormRef 代表验证规则
  if (!ruleFormRef) return; // 为空就结束，直观效果就是不允许点击
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      console.log("开始添加");
      console.log(JSON.stringify(data.form));
      data.form.claimReportId = data.dispatchForm.claimReportId;
      uu.post("/busSurveyInfo/add", data.form).then((result) => {
        if (result.ok) {
          data.dialogVisible = false; // 关闭添加对话框
          //   需要补上 增加成功的提示
          ElMessage({
            message: result.message,
            type: "success",
          });
        } else {
          ElMessage.error(result.message);
        }
        /*
            清除残留验证规则信息，让下次打开不会有上次的残留信息
            特别注意，ref的东西，在外部引用要加value，内部不用加，
            例如这里的参数就有 ruleFormRef ，所以就不用加value，否则就会出现未定义的错误。
         */
        ruleFormRef.resetFields();
        data.from = {}; // 清楚已有缓存，因为其他区域也在使用该对象数据。
        // 重新刷新页面
        queryAll();
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 修改查勘记录
 */
const handleEdit = (ruleFormRef) => {
  /*
      validate() 表单验证方法，用于验证规则是否被满足
      valid 表示验证的结果  fields 包含验证失败的错误信息
   */
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      uu.put("/busSurveyInfo/update", data.form).then((result) => {
        // data.success = result.ok;
        if (result.ok) {
          ElMessage({
            message: result.message,
            type: "success",
          });
          //   清除缓存
          data.form = {};
          //   刷新页面
          queryAll();
          //   关闭对话框
          data.dialogVisible = false;
        } else {
          ElMessage.error(result.message);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * 查询我的调度信息
 */
const queryForDispatchList = () =>
  uu.get("/busSurveyInfo/queryForDispatchList").then((result) => {
    data.dispatchList = result.data;
    // console.log(result.data)
    // console.log("--------"+JSON.stringify(data.dispatchList))
  });
/*
 根据查询到的调度信息去查询保单以及报案信息
 */
const queryClaimAndPolicy = () => {
  let dispatchId = data.form.dispatchId;
  if (data.form.dispatchId != null) {
    uu.get("/busSurveyInfo/queryClaimAndPolicy/" + dispatchId).then(
      (result) => {
        data.dispatchForm = result.data;
        console.log(result.data);
        // 按钮不再禁用
        data.isDisable = false;
      }
    );
  } else {
    ElMessage.error("id为空，事件执行失败");
  }
};
/**
 * export 导出事件
 */
const surveyExport = (id) => {
  if (id != null && id != "") {
    uu({
      method: "get",
      url: "/busSurveyInfo/surveyExportExc/" + id,
      // params:id,
      responseType: "blob", //定义为blob
    }).then((result) => {
      let blob = new Blob([result]);
      let downloadElement = document.createElement("a");
      let href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = "查勘报告.xlsx"; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    });
  } else {
    ElMessage.error("导出事件执行失败，缺少id");
  }
};
// 添加保单验证规则
const ruleFormRef = ref(); // 引用表单组件
const rules = reactive({
  // 验证规则对象，存储验证规则。
  surveyType: [{ required: true, message: "请选择查勘等级", trigger: "blur" }],
  estimatedCost: [
    { required: true, message: "请输入预估费用", trigger: "blur" },
  ],
  affectedArea: [
    { required: true, message: "请输入受灾面积", trigger: "blur" },
  ],
  deathsNumber: [
    { required: true, message: "请输入死亡数量", trigger: "blur" },
  ],
  reportedLoss: [
    { required: true, message: "请输入报损金额", trigger: "blur" },
  ],
  surveyTime: [
    {
      type: "date",
      required: true,
      message: "请选择查勘日期",
      trigger: "change",
    },
  ],
  affectedConfirmArea: [
    { required: true, message: "请输入成灾面积", trigger: "blur" },
  ],
  killQuantity: [
    { required: true, message: "请输入扑杀数量", trigger: "blur" },
  ],
  estimatedAmount: [
    { required: true, message: "请输入预估金额", trigger: "blur" },
  ],
  estimatedNumber: [
    { required: true, message: "请输入估损数量", trigger: "blur" },
  ],
  productionArea: [
    { required: true, message: "请输入绝产面积", trigger: "blur" },
  ],
  surveyIndex: [{ required: true, message: "请输入实际指数", trigger: "blur" }],
  remark: [{ required: true, message: "请输入备注信息", trigger: "blur" }],
});
</script>

<template>
  <!------------------------------ 查勘信息组件 ----------------------------------->
  <!-- 顶部区域 -->
  <el-form
    :inline="true"
    :model="data.form"
    class="demo-form-inline"
    style="width: 100%"
  >
    <!-- 便捷查询区域-->
    <div>
      <el-form-item label="报案号">
        <el-input
          v-model="data.form.claimReportId"
          placeholder="请输入报案号"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryAll()">查勘信息查询</el-button>
      </el-form-item>
    </div>
    <!--  </el-form>-->
    <!-- 添加按钮区域 -->
    <div>
      <!-- 开启添加对话框(增加或修改)==》查勘记录 -->
      <el-form-item>
        <el-button type="success" @click="dialogBox((isAdd = true), null)"
          >添加查勘信息</el-button
        >
      </el-form-item>
      <!-------------------------------- 对话框操作数据(增加或修改) -------------------------------->
      <el-dialog
        v-model="data.dialogVisible"
        :title="data.isAdd ? '增加查勘信息' : '修改查勘信息'"
        width="50%"
        :before-close="handleClose"
        draggable
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <!-- 对话款数据区域 -->
        <el-form
          :model="data.form"
          ref="ruleFormRef"
          :rules="rules"
          label-width="150px"
        >
          <!--    选择调度信息    -->
          <el-form-item label="选择调度任务" prop="ggg">
            <el-select
              v-model="data.form.dispatchId"
              filterable
              remote
              reserve-keyword
              remote-show-suffix
              @change="queryClaimAndPolicy()"
              style="width: 90%"
              placeholder="请选择调度任务"
            >
              <el-option
                v-for="item in data.dispatchList"
                :label="
                  item.claimReport
                    ? item.claimReport.claimReportId +
                      '->' +
                      item.claimReport.contactPerson +
                      '->' +
                      item.claimReport.lossAddress
                    : ''
                "
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="报案编号"
            prop="claimReportId"
            style="width: 100%"
          >
            <span v-if="data.dispatchForm.claimReportId != null">
              {{ data.dispatchForm.claimReportId }}</span
            >
            <!--            {{data.dispatchForm.claimReportId}}-->
          </el-form-item>
          <el-form-item
            label="保单编号"
            prop="policyNumber"
            style="width: 100%"
          >
            <span v-if="data.dispatchForm.claimReport != null">{{
              data.dispatchForm.claimReport.policyNumber
            }}</span>
          </el-form-item>
          <el-form-item
            label="产品名称"
            prop="insuranceType"
            style="width: 100%"
          >
            <span v-if="data.dispatchForm.busInsurancePolicy != null">{{
              data.dispatchForm.busInsurancePolicy.insuranceType
            }}</span>
          </el-form-item>
          <el-form-item label="投保人" prop="insuredName" style="width: 100%">
            <span v-if="data.dispatchForm.busInsurancePolicy != null">
              {{ data.dispatchForm.busInsurancePolicy.insuredName }}
            </span>
          </el-form-item>
          <el-form-item
            label="投保金额"
            prop="insuranceAmount"
            style="width: 100%"
          >
            <span v-if="data.dispatchForm.busInsurancePolicy != null">{{
              data.dispatchForm.busInsurancePolicy.insuranceAmount
            }}</span>
          </el-form-item>
          <el-form-item label="出险时间" prop="ii" style="width: 100%">
            <span v-if="data.dispatchForm.claimReport != null">{{
              data.dispatchForm.claimReport.lossTime
            }}</span>
          </el-form-item>

          <el-form-item label="查勘等级" prop="surveyType" style="width: 80%">
            <el-select
              :disabled="data.isDisable"
              v-model="data.form.surveyType"
              placeholder="请选择"
            >
              <el-option label="一级" value="1" />
              <el-option label="二级" value="2" />
              <el-option label="三级" value="3" />
            </el-select>
          </el-form-item>

          <el-form-item
            label="预估费用"
            prop="estimatedCost"
            style="width: 80%"
          >
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.estimatedCost"
              placeholder="请输入预估费用"
            />
          </el-form-item>

          <el-form-item label="受灾面积" prop="affectedArea" style="width: 80%">
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.affectedArea"
              placeholder="请输入受灾面积"
            />
          </el-form-item>

          <el-form-item label="死亡数量" prop="deathsNumber" style="width: 80%">
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.deathsNumber"
              placeholder="请输入死亡数量"
            />
          </el-form-item>

          <el-form-item label="报损金额" prop="reportedLoss" style="width: 80%">
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.reportedLoss"
              placeholder="请输入报损金额"
            />
          </el-form-item>

          <el-form-item label="查勘日期" prop="surveyTime" style="width: 80%">
            <el-date-picker
              :disabled="data.isDisable"
              v-model="data.form.surveyTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item
            label="成灾面积"
            prop="affectedConfirmArea"
            style="width: 80%"
          >
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.affectedConfirmArea"
              placeholder="请输入成灾面积"
            />
          </el-form-item>

          <el-form-item label="扑杀数量" prop="killQuantity" style="width: 80%">
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.killQuantity"
              placeholder="请输入扑杀数量"
            />
          </el-form-item>

          <el-form-item
            label="预估金额"
            prop="estimatedAmount"
            style="width: 80%"
          >
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.estimatedAmount"
              placeholder="请输入预估金额"
            />
          </el-form-item>

          <el-form-item
            label="估损数量"
            prop="estimatedNumber"
            style="width: 80%"
          >
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.estimatedNumber"
              placeholder="请输入估损数量"
            />
          </el-form-item>

          <el-form-item
            label="绝产面积"
            prop="productionArea"
            style="width: 80%"
          >
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.productionArea"
              placeholder="请输入绝产面积"
            />
          </el-form-item>

          <el-form-item label="实际指数" prop="surveyIndex" style="width: 80%">
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.surveyIndex"
              placeholder="请输入实际指数"
            />
          </el-form-item>

          <el-form-item label="备注" prop="remark" style="width: 80%">
            <el-input
              :disabled="data.isDisable"
              v-model="data.form.remark"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose()">取消</el-button>
            <el-button
              type="primary"
              @click="data.isAdd ? save(ruleFormRef) : handleEdit(ruleFormRef)"
            >
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-form>
  <!-- 查勘信息表格区域 -->
  <el-table :data="data.surveyList" border style="width: 100%">
    <el-table-column label="序号" type="index" fixed width="80" height="100" />
    <el-table-column
      label="报案号"
      prop="claimReportId"
      fixed
      width="250"
      height="100"
    />
    <!--    <el-table-column label="调度员" prop="busDispatchInfo." width="270" />-->
    <el-table-column label="查勘等级" prop="surveyType" width="120" />
    <el-table-column label="报损金额" prop="reportedLoss" width="120" />
    <el-table-column label="预估金额" prop="estimatedAmount" width="120" />
    <el-table-column label="预估费用" prop="estimatedCost" width="120" />
    <el-table-column label="查勘日期" prop="surveyTime" width="220" />
    <el-table-column label="估损数量" prop="estimatedNumber" width="120" />
    <el-table-column label="查勘受灾面积" prop="affectedArea" width="120" />
    <el-table-column
      label="查勘成灾面积"
      prop="affectedConfirmArea"
      width="120"
    />
    <el-table-column label="查勘绝产面积" prop="productionArea" width="120" />
    <el-table-column label="查勘死亡数量" prop="deathsNumber" width="120" />
    <el-table-column label="查勘扑杀数量" prop="killQuantity" width="120" />
    <el-table-column label="查勘实际指数" prop="surveyIndex" width="120" />
    <el-table-column label="备注" prop="remark" width="320" />
    <el-table-column label="操作" fixed="right" width="300">
      <template #default="scope">
        <!-- 点击开启对话框
                 -->
        <el-button
          @click="dialogBox(false, scope.row.id)"
          size="small"
          type="warning"
          >修改
        </el-button>
        <el-popconfirm
          @confirm="delBusiness(scope.row.id)"
          title="你确定要删除吗？"
        >
          <template #reference>
            <el-button size="small" type="danger" :plain="true"
              >Delete</el-button
            >
          </template>
        </el-popconfirm>
        <el-button
          @click="surveyExport(scope.row.id)"
          size="small"
          type="success"
          >导出查勘报告
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页区域 -->
  <div style="width: 100%">
    <br />
    <el-pagination
      v-model:current-page="data.form.pageNum"
      v-model:page-size="data.form.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :small="false"
      :disabled="disabled"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.total"
      @size-change="pagesChange($event)"
      @current-change="pagesChange($event)"
    />
  </div>
</template>

<style scoped>
.sync-dialog__div {
  height: 300px;
  overflow: auto;
}
</style>